using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using RAG.Application.Interfaces;
using RAG.Application.Dtos;

namespace RAG.Api.Controllers;

/// <summary>
/// 问答管理控制器
/// </summary>
[ApiController]
[Route("api/qa-management")]
[Authorize]
public class QAManagementController : ControllerBase
{
    private readonly IAppQAManagementService _qaManagementService;

    public QAManagementController(IAppQAManagementService qaManagementService)
    {
        _qaManagementService = qaManagementService;
    }

    /// <summary>
    /// 获取问答列表
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetQAList([FromQuery] QAListQueryDto query)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.GetQAListAsync(userId, query);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"获取问答列表时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取问答详情
    /// </summary>
    [HttpGet("{qaId}")]
    public async Task<IActionResult> GetQADetail(Guid qaId)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.GetQADetailAsync(userId, qaId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"获取问答详情时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 删除问答
    /// </summary>
    [HttpDelete("{qaId}")]
    public async Task<IActionResult> DeleteQA(Guid qaId)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.DeleteQAAsync(userId, qaId);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"删除问答时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 批量删除问答
    /// </summary>
    [HttpDelete("batch")]
    public async Task<IActionResult> BatchDeleteQA([FromBody] BatchDeleteQADto dto)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.BatchDeleteQAAsync(userId, dto.Ids);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"批量删除问答时发生错误: {ex.Message}" });
        }
    }



    /// <summary>
    /// 获取问答总数（全库）
    /// </summary>
    [HttpGet("statistics")]
    public async Task<IActionResult> GetQAStatistics()
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                // 即使无法解析用户，也返回总数（该接口不做权限限制）
                userId = Guid.Empty;
            }

            var result = await _qaManagementService.GetQAStatisticsAsync(userId);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"获取问答总数时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 导出问答数据
    /// </summary>
    [HttpPost("export")]
    public async Task<IActionResult> ExportQAData([FromBody] ExportQADto exportDto)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.ExportQADataAsync(userId, exportDto);
            
            if (result.Code == 200)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"导出问答数据时发生错误: {ex.Message}" });
        }
    }

    /// <summary>
    /// 搜索问答
    /// </summary>
    [HttpGet("search")]
    public async Task<IActionResult> SearchQA([FromQuery] string keyword, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        try
        {
            var userIdClaim = User.FindFirst("sub")?.Value
                ?? User.FindFirst("user_id")?.Value
                ?? User.FindFirst("uid")?.Value;

            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                return BadRequest(new { code = 400, message = "无法获取用户信息" });
            }

            var result = await _qaManagementService.SearchQAAsync(userId, keyword, page, pageSize);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { code = 500, message = $"搜索问答时发生错误: {ex.Message}" });
        }
    }
}
